class Cartasur::MeasurementsTag <MeasurementsTag
  establish_connection "cartasur_#{Rails.env}"


  attr_accessible :begin_id, :context, :created_at, :end_id, :tag_name, :track, :user

  belongs_to  :track
  belongs_to :user


  def geolocate
    #find the locaion based on where it started
    mymeasurestarts = Cartasur::Measure.find(self.begin_id)
    mymeasure = Cartasur::Measure.find(self.begin_id)
    location = get_location(mymeasure)

    location
  end

  #method first_geom - returns the first geometry associated with the begin_id
  def first_geom
    measures = self.end_id == -1 ?  Cartasur::Measure.where("id =#{self.begin_id} AND geom IS NOT NULL")
        :  Cartasur::Measure.where("id between #{self.begin_id} AND #{self.end_id} AND geom IS NOT NULL")
    measures.first.try(:geom)
  end

  # measures - gets all the measures for this tag
  def measure
    self.end_id == -1 ? Cartasur::Measure.where(" measures.id = #{self.begin_id}" ).all  :
                      Cartasur::Measure.where(" id BETWEEN #{self.begin_id} AND #{self.end_id}").all
  end

  #the number of measures that this tag represents
  def measures_count
     1 if self.end_id == -1
    end_id - begin_id
  end

  # measures - gets all the measures for this tag that are geo-located
  def geo_measures
    Cartasur::Measure.where(" ( (measures.id = #{self.begin_id} AND measures.end_id = -1) OR (measures.id BETWEEN  #{self.begin_id} AND #{self.end_id}) ) AND measures.geom IS NOT NULL")
  end

  def self.save_tags_as_transactions(sql_start, sql_values)
    ids = []
    sql = sql_start << sql_values.join(",") << " RETURNING id"
    self.transaction do
      result = self.connection.execute sql
      #return ids as array
      result.each do |row|
        ids << row["id"] unless row["id"].nil?
      end
    end
    ids
  end


end
